package base.集合;

import java.util.*;
import java.util.function.BiConsumer;

public class HashMap_TreeMap练习 {
    public static void main(String[] args) {
        /*
            某个班级80名学生，现在需要组成秋游活动，
            班长提供了四个景点（ A , B , C , D）   ;
            每个学生只能选择一个景点，请统计出最终哪个景点想去的人数最多；
         */

        //1.先让同学投票；
        for (int i = 0;i<3 ;i++) {
            String[] arr = {"A", "B", "C", "D"};
            ArrayList<String> list = new ArrayList<>();
            Random random = new Random();
            //通过索引添加到list集合中，模拟投票结果
            for (int q = 0; q < 80; q++) {
                int index = random.nextInt(arr.length);
                list.add(arr[index]);
            }

            //2.Map双列集合统计各景点key的票数；(添加进HashMap)
            HashMap<String, Integer> hm = new HashMap<>();
            for (String name : list) {
                if (hm.containsKey(name)) {
                    int value = hm.get(name);
                    value++;
                    hm.put(name, value);
                } else {
                    hm.put(name, 1);
                }
            }

            //3.计算最大值；
            int max = 0;
            Set<Map.Entry<String,Integer>> entries = hm.entrySet();
            for (Map.Entry<String,Integer> entry : entries){
                if (entry.getValue() > max){
                    max = entry.getValue();
                }
            }
            System.out.println(hm);

            String name = "";
            for (Map.Entry<String,Integer> entry : entries){
                if (entry.getValue() == max){
                    name += entry.getKey() + ",";
                }
            }
            System.out.println("最终选票为"+ name + "其票数：" + max);
        }


        //二、
        String s = "Hello word! ";
        TreeMap<Character,Integer> tm = new TreeMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (tm.containsKey(c)){
                //exist
                int count = tm.get(c);
                count++;
                tm.put(c,count);
            }else {
                //absent
                tm.put(c,1);
            }
        }
        System.out.println(tm);
        StringBuilder sb = new StringBuilder();
        tm.forEach(new BiConsumer<Character, Integer>() {
            @Override
            public void accept(Character key, Integer value) {
                sb.append(key).append(" (").append(value).append(") ");
            }
        });
        System.out.println(sb);
    }
}
